// https://www.lintcode.com/problem/flatten-binary-tree-to-linked-list/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    public void flatten(TreeNode root) {
        // write your code here
        List<Integer> list = new ArrayList<>();
        pre_order(root, list);
        TreeNode prev = root;
        for (int i = 1; i < list.size(); ++i) {
            TreeNode next = new TreeNode(list.get(i));
            prev.left = null;
            prev.right = next;
            prev = next;
        }
    }
    
    private void pre_order(TreeNode root, List<Integer> list) {
        if (root != null) {
            list.add(root.val);
            pre_order(root.left, list);
            pre_order(root.right, list);
        }
    }
}